﻿using Azure;
using MediatR;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using S.Common.helper;
using S.Weaning.Domain;
using S.Weaning.Infrastructure.Interface;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using static S.Weaning.ApI.Application.Command.LambWeaningCommand;
using Newtonsoft.Json;
using S.Weaning.Domain.Dto;
using System;
using Microsoft.EntityFrameworkCore;
using System.Transactions;
using static S.Weaning.ApI.Application.CommandHandlers.MaternalWeaningCommandHandler;
using S.Common.EditReproductivePresenceStateHelper;
using MathNet.Numerics.Distributions;
using Org.BouncyCastle.Utilities.Encoders;

namespace S.Weaning.ApI.Application.CommandHandlers
{
    public class LambWeaningCommandHandler : IRequestHandler<AddLambWeaningCommand, int>,IRequestHandler<DelLambWeaningCommand,bool>,IRequestHandler<UpdLambWeaningCommand,bool>
    {
        private readonly ILambAblactationRepository lambAblactationRepository;
        private readonly IConfiguration configuration;
        private readonly IHttpContextAccessor httpContextAccessor;

        public LambWeaningCommandHandler(ILambAblactationRepository lambAblactationRepository, IConfiguration configuration,IHttpContextAccessor httpContextAccessor)
        {
            this.lambAblactationRepository = lambAblactationRepository;
            this.configuration = configuration;
            this.httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 羔羊断奶批量添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<int> Handle(AddLambWeaningCommand request, CancellationToken cancellationToken)
        {
            string authHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer "))
            {
                authHeader = authHeader.Substring("Bearer ".Length).Trim();
            }
            string Gateway = configuration.GetValue<string>("Gateway");
            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    List<LambAblactationModel> lambweaningModes = new List<LambAblactationModel>();
                    var jsonString = HttpClientHelper.GetResponse(Gateway+ "/ParturitionRead/api/Parturition/GetLambList");

                    foreach (var a in request.lambweaning)
                    {
                        var response = JsonConvert.DeserializeObject<List<LambListDto>>(jsonString).FirstOrDefault(t => t.EarTag == a.EarTag);
                        LambAblactationModel maternalweanimg = new LambAblactationModel()
                        {
                            WeaningDate = request.WeaningDate,
                            DocumentNumber = request.DocumentNumber,
                            SerialNumber = request.SerialNumber,
                            Notes = request.Notes,
                            EITag = a.EITag,
                            EarTag = a.EarTag,
                            MammalianNumber = response.MotherEar,
                            WeaningDayAge = (request.WeaningDate.Value.Date - response.BirthDate.Date).Days,
                            Sex = a.Sex,
                            TurnOutBuild = a.TurnOutBuild,
                            TurnOutHuts = a.TurnOutHuts,
                            TransferBuilding = a.TransferBuilding,
                            TransferField = a.TransferField,
                            Parity = a.Parity,
                            WeaningWeight = a.WeaningWeight,
                            CreateBy = a.CreateBy,
                            CreateDate = DateTime.Now,
                        };

                        lambweaningModes.Add(maternalweanimg);

                        // 批量档案修改状态
                        parms parms = new parms()
                        {
                            earTag = new List<string> { a.EarTag },
                            wanderReproductiveState = 6,
                        };
                        HttpClientHelper.PutDataResponse(Gateway + "/achs/api/SheepFileModel/WanderStateEditPL", parms);

                        //修改羔羊状态
                        State state = new State()
                        {
                            earTag = new List<string> { a.EarTag },
                        };
                        HttpClientHelper.PostResponse(Gateway + "/ParturitionSet/api/Parturition/UpdateLambStateAll", state);

                        //HttpClientHelper.PostResponse(Gateway + "/ParturitionSet/api/Parturition/UpdateLambState?earTag=" + a.EarTag, "");

                        // 批量添加转舍记录
                        TransferRecords transfer = new TransferRecords()
                        {
                            EarTag = a.EarTag,
                            SurrenderDate = DateTime.Now,
                            RoundType = 6,
                            TurnOutBuild = Convert.ToInt32(a.TurnOutBuild),
                            TurnOutHuts = Convert.ToInt32(a.TurnOutHuts),
                            TurnOuBuildingManagementId = Convert.ToInt32(a.TurnOutBuild),
                            TurnOuColumnManagementId = Convert.ToInt32(a.TurnOutHuts),
                            ShiftToBuild = Convert.ToInt32(a.TransferBuilding),
                            ShiftToHuts = Convert.ToInt32(a.TransferField),
                            ShiftToBuildingManagementId = Convert.ToInt32(a.TransferBuilding),
                            ShiftToColumnManagementId = Convert.ToInt32(a.TransferField),
                            CreateBy = a.CreateBy,
                            CreateDate = DateTime.Now,
                        };
                        Transfer sheep = new Transfer();
                        sheep.sheep.Add(transfer);
                        HttpClientHelper.PostResponseKey(Gateway + "/transfer/api/TransFer/CreateSheepTransFers", sheep);
                    }

                    int rowsAffected = lambAblactationRepository.AddLambAblactation(lambweaningModes);
                    scope.Complete();

                    return rowsAffected;
                }
                catch (Exception ex)
                {
                    // 发生异常时回滚事务
                    scope.Dispose();
                    throw ex;
                }
            }
           
        }
        /// <summary>
        /// 羔羊断奶信息批量删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> Handle(DelLambWeaningCommand request, CancellationToken cancellationToken)
        {

            string authHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            string Gateway = configuration.GetValue<string>("Gateway");
            var items = lambAblactationRepository.GetAll();
            var matchingItems = items.Where(x => request.ids.Contains(x.LambEarNumberId.ToString())).ToList();

            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {

                    foreach (var item in matchingItems)
                    {
                        lambAblactationRepository.Delete(item.LambEarNumberId);

                        // 批量档案修改状态
                        parms parms = new parms()
                        {
                            earTag = new List<string> { item.EarTag },
                            wanderReproductiveState = 5,
                        };
                        HttpClientHelper.PutDataResponse(Gateway + "/achs/api/SheepFileModel/WanderStateEditPL", parms);
                        State state = new State()
                        {
                            earTag = new List<string> { item.EarTag },
                        };
                        // 修改羔羊状态
                        HttpClientHelper.PostResponse(Gateway + "/ParturitionSet/api/Parturition/UpdateLambStateAll", state);
                       
                        // 定义并实例化 editBreeds 对象
                        editBreeds editBreed = new editBreeds();

                        // 设置 EarTag 属性的值
                        editBreed.EarTag = item.EarTag;

                        // 删除转舍记录
                        HttpClientHelper.DeleteResponse(Gateway + $"/transfer/api/TransFer/DeleteSheepTransFer?EarTag={item.EarTag}&CreateBy={item.CreateBy}");

                    }

                    scope.Complete();

                    return true;
                }
                catch (Exception ex)
                {
                    // 处理异常情况
                    // ...
                    return false;
                }
            }
        }
        /// <summary>
        /// 羔羊断奶的修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> Handle(UpdLambWeaningCommand request, CancellationToken cancellationToken)
        {
            string gateway = configuration.GetValue<string>("Gateway");
            var model = lambAblactationRepository.GetAll().FirstOrDefault(t => t.LambEarNumberId == request.LambEarNumberId);

            model.LambEarNumberId = request.LambEarNumberId;
            model.UserId = request.UserId;
            model.WeaningDate = request.WeaningDate;
            model.Notes = request.Notes;
            model.EarTag = request.EarTag;
            model.TurnOutBuild = request.TurnOutBuild;
            model.TurnOutHuts = request.TurnOutHuts;
            model.TransferBuilding = request.TransferBuilding;
            model.TransferField = request.TransferField;
            model.UpdateBy = request.UpdateBy;
            model.UpdateDate = request.UpdateDate;
            model.DocumentNumber = request.DocumentNumber;
            model.SerialNumber = request.SerialNumber;
            model.Sex = request.Sex;
            model.Parity = request.Parity;
            model.WeaningWeight = request.WeaningWeight;

            var a = lambAblactationRepository.Update(model);

            return a;
        }

        //批量修改状态
        public class parms
        {
            public List<string> earTag { get; set; }

            public int wanderReproductiveState { get; set; }
        }
        //转舍添加
        public class Transfer
        {
            public List<TransferRecords> sheep { get; set; }

            public Transfer()
            {
                sheep = new List<TransferRecords>();
            }
        }
        //修改
        public class State
        {
            public List<string> earTag { get; set; }
        }
        //批量添加转舍记录
        public class TransferRecords
        {
            /// <summary>
            /// 转舍主键，自增标识列
            /// </summary>
            public int SheepRescissionId { get; set; }
            /// <summary>
            /// 可视耳标
            /// </summary>
            public string? EarTag { get; set; }
            /// <summary>
            /// 转舍日期
            /// </summary>
            public DateTime? SurrenderDate { get; set; }
            /// <summary>
            /// 转舍类型
            /// </summary>
            public int RoundType { get; set; }
            /// <summary>
            /// 转出栋舍
            /// </summary>
            public int TurnOutBuild { get; set; }

            /// <summary>
            /// 转出栏位
            /// </summary>
            public int TurnOutHuts { get; set; }
            /// <summary>
            /// 转出栋舍主键
            /// </summary>
            public int TurnOuBuildingManagementId { get; set; }
            /// <summary>
            /// 转出栏位主键
            /// </summary>
            public int TurnOuColumnManagementId { get; set; }
            /// <summary>
            /// 转入栋舍
            /// </summary>
            public int ShiftToBuild { get; set; }
            /// <summary>
            /// 转入栏位
            /// </summary>
            public int ShiftToHuts { get; set; }
            /// <summary>
            /// 转入栋舍主键
            /// </summary>
            public int ShiftToBuildingManagementId { get; set; }
            /// <summary>
            /// 转入栏位主键
            /// </summary>
            public int ShiftToColumnManagementId { get; set; }
            /// <summary>
            /// 品种
            /// </summary>
            public string? Variety { get; set; }
            /// <summary>
            /// 创建人
            /// </summary>
            [Column(TypeName = "nvarchar(20)")]
            [MaxLength(20)]
            public string? CreateBy { get; set; }

            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime? CreateDate { get; set; }

            /// <summary>
            /// 修改人
            /// </summary>
            [Column(TypeName = "nvarchar(20)")]
            [MaxLength(20)]
            public string? UpdateBy { get; set; }

            /// <summary>
            /// 修改时间
            /// </summary>
            public DateTime? UpdateDate { get; set; }
            /// <summary>
            /// 是否删除
            /// </summary>
            public bool IsDel { get; set; }
            /// <summary>
            /// 单据号
            /// </summary>
            public long DocumentNumbe { get; set; }
            /// <summary>
            /// 羊只类型
            /// </summary>
            public string? Type { get; set; }
        }

        /// <summary>
        /// 修改种母历史记录Dto
        /// </summary>
        public class BreedingHistoryDto
        {

            /// <summary>
            /// 种母历史记录主键
            /// </summary>
            public int BDHRId { get; set; }
            /// <summary>
            /// 种母电子耳标
            /// </summary>
            public string EarTag { get; set; }
            /// <summary>
            /// 配种日期
            /// </summary>
            public DateTime BreedingDate { get; set; }
            /// <summary>
            /// 种公电子耳号
            /// </summary>
            public string BreedingRam { get; set; }
            /// <summary>
            /// 妊检日期
            /// </summary>
            public DateTime? PregnancyDate { get; set; }
            /// <summary>
            /// 妊检结果
            /// </summary>
            public int PregnancytestResult { get; set; }
            /// <summary>
            /// 分娩日期
            /// </summary>
            public DateTime? DeliveryDate { get; set; }
            /// <summary>
            /// 健羔数
            /// </summary>
            public int HealthyNumber { get; set; }
            /// <summary>
            /// 健羔总重
            /// </summary>
            public decimal TotalWeightOfHealthyLambs { get; set; }
            /// <summary>
            /// 弱羔数
            /// </summary>
            public int LambNumber { get; set; }
            /// <summary>
            /// 畸形数
            /// </summary>
            public int DeformityNumber { get; set; }
            /// <summary>
            /// 死胎数
            /// </summary>
            public int StillbirthsNumber { get; set; }
            /// <summary>
            /// 木乃伊数
            /// </summary>
            public int MummyNumber { get; set; }
            /// <summary>
            /// 畸胎数
            /// </summary>
            public int FreaksNumber { get; set; }
            /// <summary>
            /// 当前胎次
            /// </summary>
            public int CurrentPregnancy { get; set; }
            /// <summary>
            /// 断奶日期
            /// </summary>
            public DateTime? WeaningDate { get; set; }
            /// <summary>
            /// 断奶只数
            /// </summary>
            public int WeaningCount { get; set; }
            /// <summary>
            /// 断奶窝重
            /// </summary>
            public decimal TotalweaningWeightg { get; set; }
            /// <summary>
            /// 创建人
            /// </summary>
            public string CreateBy { get; set; }
            /// <summary>
            /// 创建日期
            /// </summary>
            public DateTime? CreateDate { get; set; }
            /// <summary>
            /// 修改人
            /// </summary>
            public string UpdateBy { get; set; }
            /// <summary>
            /// 修改日期
            /// </summary>
            public DateTime? UpdateDate { get; set; }
            /// <summary>
            /// 逻辑删除标志
            /// </summary>
            public bool IsDel { get; set; }
            /// <summary>
            /// 是否可编辑（默认可编辑）
            /// </summary>
            public bool IsEditor { get; set; }

        }
    }
}
